<?php


namespace App\Utils\Logic\lak;


use App\Models\lak\Residential;
use App\Utils\Lib\Redis;
use App\Models\lak\Reservation;
class RentingLogic
{
    /*
     * 房源添加
     * lak
     * */
    public static function RentAdd($data){

        $room_data = Residential::GetCreate($data);
        return $room_data;
    }

    /*
     * 房源详情
     * lak
     * */
    public static function RentDetail($room_id){
        $room_data = Residential::Getfirst(['id'=>$room_id]);
        $room_data = json_encode($room_data,JSON_UNESCAPED_UNICODE);
        $redis = Redis::createRedisObject();
        $redis->select(15);
        $key = 'details:'.$room_id;
        $data=  $redis->hgetAll($room_id);
        if (empty($data)){
            $redis->set($key, $room_data);
            $redis->persist($key);
            $room_data = $redis->GetRedis($key);
        }
        return $room_data;
    }

    /*
     * 封装原生分页
     */
    public static function paginate($page,$limit){
        if ($limit>100) $limit=100;
        $offset=($page-1)*$limit;
        return [$limit,$offset];
    }

    /*
     * 预约看房
     * lak
     * */
    public static function ReservationAddLogic($reservation_data){
        $room = Residential::Getfirst(['location'=>$reservation_data['reserve_address']]);
        if (empty($room)) throw new \Exception('没有这个地址');

        // 判断时间在不在范围
        $start_time = strtotime($room['start_time']);
        $end_time = strtotime($room['end_time']);
        if (time() < $start_time && time() > $end_time) throw new \Exception('时间不在范围');

        $name = Reservation::Getfirst(['user_name'=>$reservation_data['user_name']],['reserve_address'=>$reservation_data['reserve_address']]);
        if (!empty($name)) throw new \Exception('不能重复预约');
        $time = time();
        $time = date('Y-m-d H:i:s', $time);
        $info = [
            'user_name' => $reservation_data['user_name'],
            'phone'=>$reservation_data['phone'],
            'reserve_time' => $time,
            'reserve_umber'=>rand(1111,9999).time(),
            'reserve_address'=>$reservation_data['reserve_address']
        ];
        $reservation_data = Reservation::GetCreate($info);

        $room['flow']+=1;
        $room->save();

        $redis = Redis::createRedisObject();
        $redis->select(11);
        $key = 'flow_rank';
        $redis->zIncrBy($key,1,$room['location']);
        $redis->expire($key,3600 * 24 * 30);

        return $reservation_data;
    }



}
